package com.zxp.web.config.springSecurity.handler;

import com.alibaba.fastjson2.JSONObject;
import com.zxp.web.VO.ResultVO;
import com.zxp.web.config.springSecurity.exeptions.CustomAuthenionException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author MasterZ
 * @Date 2025/10/7 16:34
 */
@Component
public class LoginFailHandler implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String code = "500";
        String str = "";
        if (e instanceof BadCredentialsException) {
            str = "密码错误，登陆失败";
        } else if (e instanceof CredentialsExpiredException) {
            str = "密码过期，登陆失败";
        } else if (e instanceof DisabledException) {
            str = "帐户已禁用，登陆失败";
        } else if (e instanceof LockedException) {
            str = "帐户锁定，登陆失败";
        } else if (e instanceof InternalAuthenticationServiceException) {
            str = "帐户不存在，登陆失败";
        } else if (e instanceof InsufficientAuthenticationException) {
            str = "无权限访问资源";
        } else if (e instanceof CustomAuthenionException) {
            code = "600";
            str = e.getMessage();
        } else {
            str = "登陆失败";
        }
        String res = JSONObject.toJSONString(new ResultVO(code, str, null));
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
